package com.cby.operation.common.util

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.util.Xml
import android.webkit.CookieManager
import android.webkit.WebSettings
import android.webkit.WebView

object WebUtils {

    const val APP_CACAHE_DIRNAME = "/webcache"

    fun setWebSettings(webView: WebView): WebSettings? {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webView.removeJavascriptInterface("searchBoxJavaBridge_")
            webView.removeJavascriptInterface("accessibility")
            webView.removeJavascriptInterface("accessibilityTraversal")
        }

        //每次进入都要清理缓存
//        webView.clearHistory();
//        webView.clearCache(true);
//        webView.clearFormData();

        //设置scrollBar隐藏
        webView.isHorizontalScrollBarEnabled = false
        webView.isVerticalScrollBarEnabled = false
        webView.isScrollbarFadingEnabled = false
        val webSettings = webView.settings
        //setting配置
        webSettings.javaScriptEnabled = true
        webSettings.domStorageEnabled = true
        webSettings.savePassword = false
        //支持多窗口
        webSettings.setSupportMultipleWindows(true)
        webSettings.setAppCacheMaxSize((1024 * 1023 * 25).toLong())
        webSettings.textZoom = 100
        if (Build.VERSION.SDK_INT < 18) {
            webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)
        }

        //允许自动播放音视频音乐
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.mediaPlaybackRequiresUserGesture = false
        }
        /**
         * 允许第三方cookie
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true)
            //允许http/https混合内容
            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        webSettings.javaScriptCanOpenWindowsAutomatically = false
        webSettings.setSupportMultipleWindows(false)
        webSettings.cacheMode = WebSettings.LOAD_DEFAULT

        // 是否允许WebView使用File协议，移动版的Chrome默认禁止加载file协议的文件；
        webSettings.allowFileAccess = false
        if (Build.VERSION.SDK_INT >= 16) {
            webSettings.allowFileAccessFromFileURLs = false
            webSettings.allowUniversalAccessFromFileURLs = false
        }
        //设置缓存
        webSettings.databaseEnabled = true
        webSettings.setAppCacheEnabled(true)
        val cacheDirPath = webView.context
                .filesDir.absolutePath + APP_CACAHE_DIRNAME
        webSettings.setAppCachePath(cacheDirPath)
        //屏幕自适应
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.setSupportZoom(false)
        webSettings.builtInZoomControls = false
        webSettings.setNeedInitialFocus(false)
        webSettings.defaultTextEncodingName = Xml.Encoding.UTF_8.toString()
        return webSettings
    }

    fun clearDataAndCache(webView: WebView) {
        //清除缓存
        webView.clearCache(true)
        webView.clearFormData()
        webView.clearHistory()
    }

    /**
     * 打开一个链接
     *
     * @param context
     * @param url
     */
    fun openUrl(context: Context, url: String) {
        val intent = Intent()
        intent.action = "android.intent.action.VIEW"
        val uri = Uri.parse(url)
        intent.data = uri
        if (context.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            context.startActivity(intent)
        } else {
            //找不到指定的activity
        }
    }
}